<div class="alert">
<?php
require_once('includes/user_manage.php');

$user->isAdmin or exit("Área reservada a administradores");

if (isset($_POST["name"])) {
	$my_item=new admin_item();
	$my_item->name=$_POST["name"];
	$my_item->category_id=$_POST["category_id"];
	$my_item->sort_order=$_POST["sort_order"];
	$my_item->status=1;
	$inserted=$my_item->db_insert();
	if ($inserted) {
		$my_item->db_load();
		$serItem=json_encode($my_item);
?>
	Se ha añadido el producto.
	<form id="myAddForm"><input type="hidden" value='<?php print htmlentities($serItem); ?>' name="serItem"></form>
<?php
	}
	else {
?>
	Se ha producido un error.
<?php
	}
?>
<script type="text/javascript">
	var categoryId=<?php echo $_POST["category_id"]; ?>;

	var catalogPointer=myCatalog;
	catalogPointer=catalogPointer.moveToChildren("categoryId", categoryId);
	if (!catalogPointer.myCategory.id) {
		catalogPointer=catalogPointer.moveToChildren("selected");
		catalogPointer=catalogPointer.moveToChildren("categoryId", categoryId);
	}

	var serItem=document.getElementById("myAddForm").serItem.value;
	var myItem=new adminItem();
	myItem.parentNode=catalogPointer;
	myItem.setFromArray(JSON.parse(serItem));
	catalogPointer.items.push(myItem);
	
	catalogPointer.refreshItemsListView("containerItems");
	Aelements=myItem.myView.getElementsByTagName("a");
	Aelements.item(0).focus();

window.setTimeout(removeAlert,2000,document.getElementById('addItem'));
function removeAlert(alert) {
	alert.parentNode.removeChild(alert);
}
</script>
<?php
}
else {
?>
	<form method="post" action="?section=add_item" myFor="addItem" id="addItemForm">
	<input type="hidden" value="" name="sort_order">
	<input type="hidden" value="<?php print $_GET["category_id"]; ?>" name="category_id">
	<table class="mytable">
		<tr>
			<td colspan="2">Nuevo producto</td>
		</tr>
		<tr>
			<td colspan="2"><label>Nombre: <input type="text" name="name" value=""></label></td>
		</tr>
		<tr>
			<td><input type="submit" value="Aceptar"></td>
			<td><input type="button" value="Cerrar" myFor="addItem"></td>
		</tr>
	</table>
	</form>
<script type="text/javascript">
	var categoryId=null;
	var catalogPointer=myCatalog;
	catalogPointer=catalogPointer.moveToChildren("selected");
	if (catalogPointer.myCategory.selected) {
		catalogPointer=catalogPointer.moveToChildren("selected");
	}
	categoryId=catalogPointer.myCategory.id;
	
var maxOrder=0;

for (var i in catalogPointer.items) {
	if (catalogPointer.items[i].sort_order > maxOrder) maxOrder=catalogPointer.items[i].sort_order;
}

var sortOrder=Number(maxOrder) + 1;
var myForm=document.getElementById("addItemForm");
myForm.sort_order.value=sortOrder;
myForm.name.focus();
</script>
<?php
}
?>
</div>